package com.example.myblog.controller;

import com.example.myblog.model.Category;
import com.example.myblog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类管理控制器
 */
@Controller
@RequestMapping("/admin/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    
    /**
     * 显示分类管理页面
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping
    public String listCategories(Model model) {
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("category", new Category());
        return "admin/categories";
    }
    
    /**
     * 创建新分类
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public String createCategory(@ModelAttribute Category category, RedirectAttributes redirectAttributes) {
        try {
            // 检查分类名称是否已存在
            Category existingCategory = categoryService.getCategoryByName(category.getName());
            if (existingCategory != null) {
                redirectAttributes.addFlashAttribute("error", "分类名称已存在！");
                return "redirect:/admin/categories";
            }
            
            categoryService.saveCategory(category);
            redirectAttributes.addFlashAttribute("message", "分类创建成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "分类创建失败：" + e.getMessage());
        }
        return "redirect:/admin/categories";
    }
    
    /**
     * 显示编辑分类表单
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/{id}/edit")
    public String showEditForm(@PathVariable Long id, Model model) {
        Category category = categoryService.getCategoryById(id);
        if (category == null) {
            return "redirect:/admin/categories";
        }
        model.addAttribute("category", category);
        model.addAttribute("categories", categoryService.getAllCategories());
        return "admin/categories";
    }
    
    /**
     * 更新分类
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{id}")
    public String updateCategory(@PathVariable Long id, @ModelAttribute Category category, RedirectAttributes redirectAttributes) {
        try {
            // 检查分类是否存在
            Category existingCategory = categoryService.getCategoryById(id);
            if (existingCategory == null) {
                redirectAttributes.addFlashAttribute("error", "分类不存在！");
                return "redirect:/admin/categories";
            }
            
            // 检查名称是否与其他分类重复
            Category categoryWithSameName = categoryService.getCategoryByName(category.getName());
            if (categoryWithSameName != null && !categoryWithSameName.getId().equals(id)) {
                redirectAttributes.addFlashAttribute("error", "分类名称已存在！");
                return "redirect:/admin/categories";
            }
            
            category.setId(id);
            categoryService.saveCategory(category);
            redirectAttributes.addFlashAttribute("message", "分类更新成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "分类更新失败：" + e.getMessage());
        }
        return "redirect:/admin/categories";
    }
    
    /**
     * 删除分类
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{id}/delete")
    public String deleteCategory(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            categoryService.deleteCategory(id);
            redirectAttributes.addFlashAttribute("message", "分类删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "分类删除失败：" + e.getMessage());
        }
        return "redirect:/admin/categories";
    }
    
    /**
     * 处理分类排序请求
     * @param categoryIds 排序后的分类ID列表
     * @return 操作结果
     */
    @PostMapping("/reorder")
    @PreAuthorize("hasRole('ADMIN')")
    @ResponseBody
    public ResponseEntity<?> reorderCategories(@RequestBody List<Long> categoryIds) {
        try {
            // 更新分类的显示顺序
            for (int i = 0; i < categoryIds.size(); i++) {
                categoryService.updateCategoryDisplayOrder(categoryIds.get(i), i);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "分类排序更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "分类排序更新失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}